from app import db
from datetime import datetime
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

class Question(db.Model):
    __tablename__ = 'question'
    
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False)
    answer = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    is_active = db.Column(db.Boolean, default=True)

class Config(db.Model):
    __tablename__ = 'config'
    
    id = db.Column(db.Integer, primary_key=True)
    key = db.Column(db.String(50), unique=True, nullable=False)
    value = db.Column(db.String(255), nullable=False)

class DrawRecord(db.Model):
    __tablename__ = 'draw_record'
    
    id = db.Column(db.Integer, primary_key=True)
    question_ids = db.Column(db.String(200), nullable=False)
    student_id = db.Column(db.String(20), nullable=False)
    user_token = db.Column(db.String(100), nullable=False)
    ip_address = db.Column(db.String(50), nullable=False)
    user_agent = db.Column(db.String(1000), nullable=False)
    draw_time = db.Column(db.DateTime, default=datetime.utcnow)
    is_redraw = db.Column(db.Boolean, default=False)
    
    def get_question_ids(self):
        return [int(id) for id in self.question_ids.split(',')]

    def set_question_ids(self, ids):
        self.question_ids = ','.join(map(str, ids))

    @property
    def questions(self):
        return Question.query.filter(Question.id.in_(self.get_question_ids())).all()

class InviteCode(db.Model):
    __tablename__ = 'invite_codes'
    
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(32), unique=True, nullable=False)
    is_used = db.Column(db.Boolean, default=False)
    created_by = db.Column(db.String(64), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    used_by = db.Column(db.String(64))
    used_at = db.Column(db.DateTime)
    
    def __repr__(self):
        return f'<InviteCode {self.code}>'

class Admin(UserMixin, db.Model):
    __tablename__ = 'admin'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    role = db.Column(db.String(20), default='staff')  # 'super' or 'staff'
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    
    def is_super_admin(self):
        return self.role == 'super' 